const _ = require('lodash')
const path = require('path')
const fs = require('fs')
const glob = require('glob')
const currentPath = path.resolve(__dirname, './test/')
//const currentPath = path.resolve(__dirname, '../../../zhuanti_vue3/src/pages/shop10/')
// const currentPath = path.resolve(__dirname, '../../../shop10/')
const checkFileIsNew = (basename) => {
  return /0_\d{3}_/.test(basename)
}

const getBaseName = (basename) => {
  if (checkFileIsNew(basename)) {
    return basename.replace(/0_\d{3}_/, '')
  } else {
    return basename
  }
}

const readFile = () => {
  let files = glob.sync('**/*.{png,jpg,jpeg,mp3}', {
    cwd: currentPath,
    ignore: ['**/swiper/**', '**/images/**', '**/p1.jpg']
  })
  //搜索信息
  const bigData = {}
  files.forEach((res) => {
    let dirname = path.dirname(res)
    let ofile = path.basename(res)
    let basename = getBaseName(ofile)
    let currentDir = (bigData[dirname] = bigData[dirname] || {
      dir: dirname,
      list: []
    })
    const order = currentDir.list.length
    currentDir.list.push({
      ofile,
      file: basename,
      dir: dirname,
      order
    })
  })
  return bigData
}

const writeFileToJson = () => {
  const data = readFile()
  let text = JSON.stringify(data)
  fs.writeFileSync(path.resolve(currentPath, 'file.json'), text, 'utf-8')
}
const readFileFromJson = () => {
  let text = fs.readFileSync(path.resolve(currentPath, 'file.json'))
  let json = JSON.parse(text)
  return json
}

const renameFile = () => {
  const bigData = readFileFromJson()
  //先修改文件名
  _.forIn(bigData, (value, key) => {
    value.list.forEach((res, i) => {
      const { order, dir, ofile, file } = res
      const newfile = '0_' + _.padStart(order, 3, '0') + '_' + file
      const ofile_path = path.resolve(currentPath, dir, ofile)
      const newfile_path = path.resolve(currentPath, dir, newfile)
      fs.renameSync(ofile_path, newfile_path)
    })
  })

  //再修改文件夹名
  _.forIn(bigData, (value, key) => {
    if (key != value.dir) {
      const newdir = path.resolve(currentPath, value.dir)
      const olddir = path.resolve(currentPath, key)
      fs.renameSync(olddir, newdir)
    }
  })
  //再重建
}

const argv = process.argv
const type = argv[2]
if (type == 'write') {
  console.log('rename')
  renameFile()
  writeFileToJson()
} else if (type == 'read') {
  console.log(`read`)
  writeFileToJson()
} else {
  console.log(`没有操作`)
}
